﻿$(function () {
    $("#optReferenceToSpecialist").attr("class", "HoverOnList");
    $("#breadcrumb").append('<li><a href="' + $("#urlReferenceSpecialist").val() + '" title="Referencia a Especialista">Referencia a Especialista</a></li>');

    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['es']);

    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    var validator1 = $("#frmPrintable").bind("invalid-form.validate", function () {
        //$("#lblError").show();
    }).validate({
        debug: true,
        rules: {
            txtPersonFilter: {
                required: true,
                minlength: 1
            },
            serviceName: {
                required: true,
                minlength: 1
            },
            specialistName: {
                required: true,
                minlength: 1
            },
            specialistCode: {
                required: true,
                minlength: 1
            },
            clinicData: {
                required: true,
                minlength: 1
            },
            reason: {
                required: true,
                minlength: 1
            },
            comments: {
                required: true,
                minlength: 1
            },
        },
        messages: {
            txtPersonFilter: "La persona es requerida",
            serviceName: "El Nombre de Serivicio es requerido",
            specialistName: "El Nombre del Especialista es requerido",
            specialistCode: "El codigo del especialista es requerido",
            clinicData: "El color anterior es requerido",
            reason: "La razon es requerido",
            comments: "El Comentario es requerido"
        }
    });

   
    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });

    $('#menuClear').click(function () {
        ClearForm();
    });

    $('#btnClear').click(function () {
        ClearForm();
    });

    $('#btnClearForm').click(function () {
        Clear();
    });

    $('#btnAdd').click(function () {
        AddRecord();
    });

    $('#btnSaveMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            if (parseInt($('#personID').val()) > 0) {
                Add();
            }
            else {
                alert('Debe seleccionar un paciente.');
            }
        }
    });

    $('#btnSave').click(function () {
        if ($("#frmPrintable").valid()) {
            if (parseInt($('#personID').val()) > 0) {
                Add();
            }
            else {
                alert('Debe seleccionar un paciente.');
            }
        }
    });

    $('#btnUpdateMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            Edit();
        }
    });

    $('#btnUpdate').click(function () {
        if ($("#frmPrintable").valid()) {
            Edit();
        }
    });

    $('#btnPrintMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            Print();
        }
    });

    $('#btnPrint').click(function () {
        if ($("#frmPrintable").valid()) {
            Print();
        }
    });

    $('#btnSearch').click(function () {
        Search();
    });

    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }

   

});



function ClearForm() {
    Clear();

    

    $('#txtServiceName').val('');
    $('#txtSpecialistName').val('');
    $('#txtSpecialistCode').val('');
    $('#txtClinicData').val('');
    $('#txtReason').val('');
    $('#txtComments').val('');

    $("#txtServiceName").removeClass("error");
    $("#txtSpecialistName").removeClass("error");
    $("#txtSpecialistCode").removeClass("error");
    $("#txtClinicData").removeClass("error");
    $("#txtReason").removeClass("error");
    $("#txtComments").removeClass("error");

    $("#frmPrintable").find(".error").remove();
}



function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        Delete(id);
    }
}

function Add() {
   

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                partyID: $('#personID').val(),
                serviceName: $('#txtServiceName').val(),
                specialistName: $('#txtSpecialistName').val(),
                specialistCode: $('#txtSpecialistCode').val(),
                clinicData: $('#txtClinicData').val(),
                reason: $('#txtReason').val(),
                comments: $('#txtComments').val(),
               
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlIndex").val();
                //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=3";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Edit() {
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlEdit").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                Address: $('#address').val(),
                Phone: $('#phone').val(),
                CompanyName: $('#companyName').val(),
                Logo: $('#logo').val(),
                MedicName: $('#txtMedicName').val(),
                MedicIdentification: $('#txtMedicIdentification').val(),
                PatientName: $('#txtPatientName').val(),
                PatientIdentification: $('#txtPatientIdentification').val(),
                partyID: $('#partyID').val(),
                companyID: $('#companyID').val(),
                createdBy: $('#createdBy').val(),
                serviceName: $('#txtServiceName').val(),
                specialistName: $('#txtSpecialistName').val(),
                specialistCode: $('#txtSpecialistCode').val(),
                clinicData: $('#txtClinicData').val(),
                reason: $('#txtReason').val(),
                comments: $('#txtComments').val(),
                referenceSpecialistID: $('#reportID').val()
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/ReferenceSpecialist/SetMessage?id=4";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/ReferenceSpecialist/SetMessage?id=2";
        }
    });
}

function Print() {
   
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlPrint").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                Address: $('#address').val(),
                Phone: $('#phone').val(),
                CompanyName: $('#companyName').val(),
                Logo: $('#logo').val(),
                MedicName: $('#txtMedicName').val(),
                MedicIdentification: $('#txtMedicIdentification').val(),
                PatientName: $('#txtPatientName').val(),
                PatientIdentification: $('#txtPatientIdentification').val(),
                partyID: $('#partyID').val(),
                companyID: $('#companyID').val(),
                createdBy: $('#createdBy').val(),
                serviceName: $('#txtServiceName').val(),
                specialistName: $('#txtSpecialistName').val(),
                specialistCode: $('#txtSpecialistCode').val(),
                clinicData: $('#txtClinicData').val(),
                reason: $('#txtReason').val(),
                comments: $('#txtComments').val(),
                referenceSpecialistID: $('#reportID').val()
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=1";
                window.location = $("#urlPrint").val(); //$("#urlIndex").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Delete(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlIndex").val();
                window.location = "/ODSYSUI/ReferenceSpecialist/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = $("#urlIndex").val();
            window.location = "/ODSYSUI/ReferenceSpecialist/SetMessage?id=2";
        }
    });
}

function InitAutocomplete() {
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {

                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#personID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#personID').val();
        }
    });
}

function Search() {
    debugger;
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                createdBy: $('#cmbMedic').val(),
                startDate: date1,
                endDate: date2,
                isByName: $('#rdbNameFilter').is(':checked'),
                personFilter: $('#txtPersonFilter').val(),
                partyID: $('#personID').val(),
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}